# This decorates Handlebars.js with the ability to load
# templates from an external source, with light caching.
#
# To render a template, pass a closure that will receive the
# template as a function parameter, eg,
#   window.T.render('templateName', function(t) {
#     $('#somediv').html( t() );
#   });

#class T
#  cached : {}
#
#  render: (name, callback) ->
#    if (window.T.isCached(name))
#      callback(window.T.cached[name])
#    else
#      $.get(window.T.urlFor(name), (raw) ->
#          window.T.store(name, raw)
#          window.T.render(name, callback)
#      , "text")
#
#  renderSync: (name, callback) ->
#    if (!window.T.isCached(name))
#      window.T.fetch(name)
#    window.T.render(name, callback)
#
#  prefetch: (name) ->
#    $.get(window.T.urlFor(name), (raw) ->
#      window.T.store(name, raw)
#    , "text")
#
#  fetch: (name) ->
#    # synchronous, for those times when you need it.
#    if (!window.T.isCached(name))
#      raw = $.ajax({'url': window.T.urlFor(name), 'async': false}).responseText
#      window.T.store(name, raw)
#
#  isCached: (name) ->
#    return !!window.T.cached[name]
#
#  store: (name, raw) ->
#    window.T.cached[name] = Handlebars.compile(raw);
#
#  urlFor: (name) ->
#    return "@@content-root@@/handlebar_templates/"+ name + ".handlebars?@@build-timestamp@@";

################################################################################################################################
# Main class that do a lot of needed things
################################################################################################################################

class Sys
  GALLERIES_IN_ROW: 4

  actualGalleriesCount = 0

#  DEFAULT_LOCALE: 'en'
#  SUPPORTED_LOCALE: ["en", "sk"]
#
#  #  Load file from path saved in 'filename'
#  loadJsCssFile: (filename, filetype) ->
#    if (filetype is 'js')
#      fileref=document.createElement('script')
#      fileref.setAttribute('type','text/javascript')
#      fileref.setAttribute('src', filename)
#
#    else if (filetype is 'css')
#      fileref=document.createElement('link')
#      fileref.setAttribute('rel', 'stylesheet')
#      fileref.setAttribute('type', 'text/css')
#      fileref.setAttribute('href', filename)
#
#    if (typeof fileref isnt 'undefined')
#      document.getElementsByTagName('head')[0].appendChild(fileref)
#
#  #  Get parameter from url with provided name or null
#  getURLParameter: (name) ->
#    decodeURIComponent((new RegExp("[?|&]#{name}=([^&;]+?)(&|##|;|$)").exec(location.search) || [null,""] )[1].replace(/\+/g, '%20'))||null;
#
#  #  Dynamically load js file with messages for selected locale (selected in url parameter)
#  loadMessagesAccordingSelectedLocale: () ->
#    locale = window.Sys.getURLParameter('locale')
#    if (-1 is $.inArray(locale, window.Sys.SUPPORTED_LOCALE))
#      locale = window.Sys.DEFAULT_LOCALE
#    # $.getJSON pathToVersionFile, (data) ->
#    #      window.Sys.loadJsCssFile(pathToMessagesParentDir + '/messages_' + locale + '.js?' + data.version, 'js')
#    window.Sys.loadJsCssFile(pathToMessagesParentDir + '/messages_' + locale + '.js?@@build-timestamp@@', 'js')
#
#  #  Translate all messages on the page (replace elements with key with normal messages)
#  translateMessagesOnThePage: () ->
#    $('msg').each ->
#      key = ($ @).data('key')
#      ($ @).replaceWith(messages[key])
#
#    # check if it is a page with submenu and extend header if it is so
#    if(submenuTitleKey?)
#      subtitle = messages[submenuTitleKey]
#      $('#header-subtitle').html('<div class="header-subtitle-panel">' + subtitle + '</div>');
#      $('.header-content').addClass('header-content-with-subtitle');
#      $('#header').addClass('header-with-subtitle');
#
#  #  When 'messages' variable is available (messages_xx.js file was loaded). Run translations.
#  startTranslationWhenReady: () ->
#    if (typeof messages != 'undefined')
#      window.Sys.translateMessagesOnThePage()
#    else
#      setTimeout('window.Sys.startTranslationWhenReady()', 100)

  #  Find data in galleries-data divs and create real gallereis from them
  createGallereisFromGallDataDivs: () ->
    $.each ($ '#galleries-data ul'), (i, selectedUl) ->

      # data is databoject that holds all information about current gallerie and will be pushed to handlebar template
      data = {}

      # pictures will be saved in special array
      data.pictures = new Array();

      #read group data first
      gallData = ($ @).children('li[data-group-img]')
      data.groupTitle = gallData.data('group-title')
      data.groupImg = gallData.data('group-img')

      #read data about all normal pictures in this gallerie
      $.each ($ @).children('li[data-img]'), (j, selectedNormalPicutreLi) ->
        if (j==0)
          data.firstTitle = ($ @).data('title')
          data.firstImg = ($ @).data('img')
        else
          data.pictures.push({'title' : ($ @).data('title'), 'img' : ($ @).data('img')})

      template = Handlebars.compile ($ '#gallery-template').html()
      ($ '#galleries').append($ template gallTemplateData: data)

      # Increment counter of galleries and add linebreak when row is finished
      actualGalleriesCount++
      if (actualGalleriesCount % window.Sys.GALLERIES_IN_ROW) == 0
        ($ '#galleries').append('<div class="new-line-div"></div>')    

  activateGalleries: () ->
    galleryIndex = 0

    ($ '#galleries').find('.gallery').each ->
      ($ @).find('li a').attr('rel', 'prettyPhoto[gallery' + galleryIndex + ']')
      galleryIndex++

    $(".gallery a[rel^='prettyPhoto']").prettyPhoto({animation_speed:'normal',theme:'pp_default',slideshow:3000, autoplay_slideshow: false, social_tools: false});

  # fit img to div with preserved ratio of dimensions
  fitImgDimensionsAccordinContainerDimensions: ($img, $container) ->
    ratioWidth = $img.width() / $container.width()
    ratioHeight = $img.height() / $container.height()
    if (ratioWidth > ratioHeight)
      $img.css('width': '100%', 'height': 'auto')
    else
      $img.css('width': 'auto', 'height': '100%')  

($ document).ready ->
  window.Sys = new Sys

  # window.T = new T
  # Loading header template
  #  window.T.render('header-template', (x) ->
  #    $('#header').append( x() )

  #  # Localizatoin stuff
  #  window.Sys.loadMessagesAccordingSelectedLocale()
  #  window.Sys.startTranslationWhenReady()

  #  changing the language
  $('.locale-changer').live 'click', ->
    locale = ($ @).data('locale')
    window.location.search = jQuery.query.set('locale', locale)
    false

  # Highlight main menu tab for actual page
  $("#" + selectedMenuId).addClass('highlighted');

  # What to do when submenu item from menu is clicked
  onselect_callback = (event, list, field, item) ->
    url = ($ item).data('url');
    window.location.href = url + window.location.search
    true

  # Add to every needed menu tab submenu according it's list of submenus
  # and to every direct menu link it's onCLick action
  withSubmenu = ['photogallery', 'my-monologues']
  withoutSubmenu = ['for-beginning', 'our-team', 'your-ideas']

  $.each withSubmenu, (i, type) ->
    menuLink = ($ '#menu-' + type + '-select')
    if menuLink.length is 1
      menuLink.css('cursor': 'default', 'text-decoration': 'none') #Disable visual signs of link
      menuLink.click ->  #Do nothing on click
        false
      menuLink.menubox
        field: type,
        onselect: onselect_callback

  $.each withoutSubmenu, (i, type) ->
    menuLink = ($ '#menu-' + type + '-select')
    if menuLink.length is 1
      menuLink.click ->
        url = ($ @).data('url')
        window.location.href = url + window.location.search
        false

  # create galleries from galleries data
  window.Sys.createGallereisFromGallDataDivs()

  # Activate potencial galleries on the page
  window.Sys.activateGalleries()

($ window).load ->
  # Fit images to for gallereis groups
  galleriesGroupsImages = ($ '.gallery-img-div img')
  $.each galleriesGroupsImages, (i, gallerieGroupImg) ->
    window.Sys.fitImgDimensionsAccordinContainerDimensions(($ @), ($ @).parent())

  # Columnize stuff
  $('.article_section h1').addClass("dontend")
  $('.article_section').columnize({columns:4, lastNeverTallest: true, target: "#article-temp-target", doneFunc: () ->
    $('#article-final-target').append('<div class="article-separator"></div>');
    $('#article-final-target').append($('#article-temp-target').html());
    $('#article-temp-target').html("");
  })


